using SimpleToDoList.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace SimpleToDoList.Services;

public static class ToDoListFileService
{
    private static readonly string _jsonFileName =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SimpleToDoList", "TodoListV2.txt");

    public static async Task<List<ToDoItem>?> ReadFileAsync()
    {
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(_jsonFileName)!);

            await using var fs = File.OpenRead(_jsonFileName);
            return await JsonSerializer.DeserializeAsync<List<ToDoItem>>(fs, new JsonSerializerOptions
                                                                             {
                                                                                 //设置中文编码，默认会转义
                                                                                 Encoder =
                                                                                     System.Text.Encodings.Web.JavaScriptEncoder.Create(
                                                                                         UnicodeRanges.All),
                                                                                 TypeInfoResolver = TodoItemSourceGenerationContext.Default
                                                                             });
            // var items = new List<ToDoItem>();
            //
            // using var reader = new StreamReader(_jsonFileName, Encoding.UTF8);
            // string? line;
            // while ((line = await reader.ReadLineAsync()) != null)
            // {
            //     var parts = line.Split(',');
            //     if (parts.Length != 2)
            //     {
            //         continue;
            //     }
            //
            //     var flag = int.TryParse(parts[0], out var isCheckedId);
            //     if (!flag)
            //         continue;
            //
            //     var name = parts[1];
            //     items.Add(new ToDoItem { IsChecked = isCheckedId == 1, Content = name });
            // }
            //
            // return items;
        }
        catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException)
        {
            return null;
        }
        catch (Exception)
        {
            return null;
        }
    }

    public static async Task SaveToFileAsync(List<ToDoItem> itemsToSave)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_jsonFileName)!);

        await using var fs = File.Create(_jsonFileName);
        await JsonSerializer.SerializeAsync(fs, itemsToSave, new JsonSerializerOptions
                                                             {
                                                                 //设置中文编码，默认会转义
                                                                 Encoder =
                                                                     System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All),
                                                                 TypeInfoResolver = TodoItemSourceGenerationContext.Default
                                                             });

        // await using var writer = new StreamWriter(_jsonFileName, false, Encoding.UTF8);
        // foreach (var item in itemsToSave)
        // {
        //     await writer.WriteLineAsync($"{(item.IsChecked ? 1 : 0)},{item.Content}");
        // }
    }
}